package com.zhi.service.impl;

import com.zhi.service.MailService;
import com.zhi.service.RunLogService;
import com.zhi.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailServiceImpl implements MailService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RunLogService runLogService;

    @Autowired
    private JavaMailSender javaMailSender;

    //发送人的邮箱
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件服务
     * Async意思是异步调用这个方法
     * @param title   标题
     * @param content 正文
     * @param email   邮箱
     */
    @Override
    @Async
    public void sendMail(String title, String content, String email) {
        SimpleMailMessage message = new SimpleMailMessage();

        //文本格式
        /*message.setFrom(from); // 发送人的邮箱
        message.setSubject(title); //标题
        message.setTo(email); //发给谁  对方邮箱
        message.setText(content); //内容
        javaMailSender.send(message); //发送*/

        //html格式
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject(title);
            helper.setText(content,true);

            logger.info("邮件发送:"+email);
            logger.info("邮件正文:"+content);

            javaMailSender.send(mimeMessage);

            LogUtil.insert(email,"email",content);

        } catch (Exception e) {

            //在此捕获所有邮件相关的异常，防止因为邮件异常影响请假流程处理
            logger.error(e.getMessage());
        }

    }
}
